//
//  AddReasonViewController.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/30.
//

import UIKit
import ReactiveCocoa
import SVProgressHUD

class AddReasonViewController: UIViewController {

    var diaryModel: DiaryModel?
    
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var btn: UIButton!
    
    var alert:CustomDialogueController?
    var saveAlert:CustomDialogueController?
    var selectArray: [String]?
    var isBadXinqing: Bool = false
    
    var tempDataArr:[[String:Any]] = AppConstant.activeDatasArr
    var reasonArray:[[[String:Any]]] = [[[String:Any]]]()
//    let reasonArray = [["工作", "学习", "音乐", "美食", "亲子", "健身", "娱乐", "购物", "电影", "旅行", "游戏", "晚餐"], ["礼物", "爱情", "关系", "阅读", "追剧", "运动", "吃瓜", "熬夜", "烹饪", "家庭", "休息", "宠物"], ["整理", "冒险", "度假", "徒步", "省钱", "露营", "生病", "骑行", "逛街", "动漫", "游泳", "变美"], ["奶茶", "茶点", "", "打坐", "养生", "", "出海", "偶像", "", "洗澡", "其它", ""]]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        selectArray = []
        self.configActiveArr()
        
        titleLabel.text = "哪些事让你" + (diaryModel?.moodStr ?? "") + "呢？"

        btn.layer.borderWidth = 0.5
        btn.layer.borderColor = UIColor.hexColor(hex: "#8f8f8f").cgColor
        btn.layer.cornerRadius = btn.fhh_height * 0.5
        
        bgView.layer.cornerRadius = 10.0
        
        textView.delegate = self
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "AddReasonCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "AddReasonCollectionViewCell")
        
    
    }
    
    //12分组是由于ui分页滚动问题
    func configActiveArr(){
        
        if var imgArray = UserDefaults.standard.array(forKey: KUSERActiveImagesArrName ) as? [[String:Any]] {
            
            if let deletedImgArray = UserDefaults.standard.array(forKey: KUSERActiveDeletedImagesArrName) as? [[String:Any]] {
                imgArray.append(contentsOf: deletedImgArray)
            }
            tempDataArr = imgArray
        }else{
            
            UserDefaults.standard.setValue(tempDataArr, forKey: KUSERActiveImagesArrName)
            UserDefaults.standard.synchronize()
        }
        
        let tempCount = tempDataArr.count%12
        
        if tempCount == 0 {
            return
        }else{
            
            for _ in 0..<(12-tempCount) {
                
                tempDataArr.append(["imgName":"","text":"","isCustom":false])
            }
        }
        
        for i in 0..<(tempDataArr.count/12) {
            
            let arr:[[String:Any]] = Array(tempDataArr[(i*12)...((i+1)*12-1)])
            reasonArray.append(arr)
        }
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        self.addShadowFunc()
    }
    
    func continueEditFunc(){
        
        let textviewCacheStr:String = UserDefaults.standard.string(forKey: textView_cache) ?? ""
        if textviewCacheStr.count > 0 {

            self.showReEditView()
        }
    }
    
    func showReEditView(){
        
        let alertC = UIAlertController.init(title: "提示", message: "是否继续上一次的编辑", preferredStyle: .alert)
        let alert = UIAlertAction.init(title: "编辑", style: .destructive) {
            (UIAlertAction) in
            
            print("确定按钮点击")
            let textviewCacheStr:String = UserDefaults.standard.string(forKey: textView_cache) ?? ""
            self.textView.text = textviewCacheStr
            self.textView.textColor = .black
            
            UserDefaults.standard.set(nil, forKey: textView_cache)
            
        }
        let cancleAlert = UIAlertAction.init(title: "取消", style: .cancel) { (UIAlertAction) in
            
            print("点击取消按钮")
        }

        alertC.addAction(cancleAlert)

        alertC.addAction(alert)

        self.present(alertC, animated: true, completion: nil)
        
    }
    
    func addShadowFunc(){
        
        let shadowLayer = CAShapeLayer.init()

        shadowLayer.frame = bgView.bounds;

        // Standard shadow stuff
        shadowLayer.shadowColor = UIColor.lightGray.cgColor
        shadowLayer.shadowOffset = CGSize(width: 0, height: 0)
        shadowLayer.shadowOpacity = 0.3
        shadowLayer.fillRule = CAShapeLayerFillRule.evenOdd
        
        let path = CGMutablePath.init()

        path.addRect(bgView.bounds.insetBy(dx: -40, dy: -40))

        let someInnerPath = UIBezierPath.init(roundedRect: CGRect.init(x: 0, y: 0, width: bgView.fhh_width, height: bgView.fhh_height), cornerRadius: 10.0).cgPath

        path.addPath(someInnerPath)
        
        path.closeSubpath()

        shadowLayer.path = path

//        CGPathRelease(path)

        bgView.layer.addSublayer(shadowLayer)

        let maskLayer = CAShapeLayer.init()

        maskLayer.path = someInnerPath

        shadowLayer.mask = maskLayer
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    // 友盟页面统计
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        MobClick.beginLogPageView("添加事情")
        MobClick.event("pages_num", attributes: ["TianJiaShiQing":"进入添加事情"])
        
//        NotificationCenter.default.rac_addObserver(forName: UIResponder.keyboardWillShowNotification.rawValue, object: nil)?.subscribeNext({ [weak self] (x) in
//
//            guard let self = self else { return }
//
//            let noti: Notification = x as! Notification
//            let time = noti.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
//            UIView.animate(withDuration: time) {
//                self.view.transform = CGAffineTransform.identity
//            }
//
//            let textFieldMaxY = self.bgView.fhh_y + self.bgView.fhh_height + CGFloat(statusAndNav_height)
//            let keyBoardMinY = (noti.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect).origin.y
//            let distance = textFieldMaxY - keyBoardMinY
//            if distance > 0 {
//                UIView.animate(withDuration: time) {
//                    self.view.transform = CGAffineTransform.init(translationX: 0, y: -distance - 25.0)
//                }
//            }
//        })
//        NotificationCenter.default.rac_addObserver(forName: UIResponder.keyboardWillHideNotification.rawValue, object: nil)?.subscribeNext({ [weak self] (x) in
//
//            guard let self = self else { return }
//
//            let noti: Notification = x as! Notification
//            let time = noti.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
//            UIView.animate(withDuration: time) {
//                self.view.transform = CGAffineTransform.identity
//            }
//        })
    }
    
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        MobClick.endLogPageView("添加事情")
        MobClick.event("pages_num", attributes: ["TianJiaShiQing":"离开添加事情"])
        
    }
}

extension AddReasonViewController {
    
    @IBAction func saveAction() {
        
        for subView in view.subviews {
            subView.isUserInteractionEnabled = false
        }
        
//        let page = Int(collectionView.contentOffset.x / collectionView.width)
        diaryModel?.reasonArray = selectArray
        if diaryModel?.createTimeStampStr == nil {
            diaryModel?.createTimeStampStr = NSString.currentTimeStamp()
        }
        
        if textView.text.count > 0 && textView.text != "有更多想告诉我的吗？" {
            diaryModel?.reasonDetailStr = textView.text
        } else {
            diaryModel?.reasonDetailStr = ""
        }
        
        do {
            let encoder = JSONEncoder()
            let data = try encoder.encode(diaryModel)
            let dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            
            let fileManager = FileManager.default
            let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
            var folderPath = docPath + "/" + NSString.currentYear()
            
            if NSString.getYear(diaryModel?.timeStampStr ?? "") != NSString.currentYear() {
                folderPath = docPath + "/" + "\((Int(NSString.currentYear()) ?? 0) - 1)"
            }

            if fileManager.fileExists(atPath: folderPath) == false {
                do {
                    try fileManager.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
                } catch {
                    print(error)
                }
            }
            let fileName = NSString.getMonth(diaryModel?.timeStampStr ?? "") + ".plist"

            let filePath = (folderPath as NSString).appendingPathComponent(fileName)

            var hisDictionary = NSMutableDictionary(contentsOfFile: filePath)
            if hisDictionary == nil {
                hisDictionary = NSMutableDictionary()
            }

            let day = NSString.getDay(diaryModel?.timeStampStr ?? "")

            var dayArray: [[String: Any]]? = hisDictionary?[day] as? [[String: Any]]
            if dayArray == nil {
                dayArray = [[String: Any]]()
            }
            dayArray?.append(dict as! [String : Any])
            hisDictionary?[day] = dayArray
            
            //日记
            let diaryFilePath = docPath + "/diary.plist"
            var diaryArr = NSMutableArray(contentsOfFile: diaryFilePath)
            if diaryArr == nil {
                diaryArr = NSMutableArray()
            }
            diaryArr?.add(dict)
            diaryArr?.write(toFile: diaryFilePath, atomically: true)

            //心情
            let moodDic = ["mood": diaryModel?.moodStr, "timeStamp": diaryModel?.timeStampStr]
            let moodFilePath = docPath + "/mood.plist"
            var moodArr = NSMutableArray(contentsOfFile: moodFilePath)
            if moodArr == nil {
                moodArr = NSMutableArray()
            }
            moodArr?.add(moodDic)
            moodArr?.write(toFile: moodFilePath, atomically: true)

            //天气
            let weatherDic = ["weather": diaryModel?.weatherStr, "timeStamp": diaryModel?.timeStampStr]
            let weatherFilePath = docPath + "/weather.plist"
            var weatherArr = NSMutableArray(contentsOfFile: weatherFilePath)
            if weatherArr == nil {
                weatherArr = NSMutableArray()
            }
            weatherArr?.add(weatherDic)
            weatherArr?.write(toFile: weatherFilePath, atomically: true)

            //活动
            let activityFilePath = docPath + "/activity.plist"
            var activityArr = NSMutableArray(contentsOfFile: activityFilePath)
            if activityArr == nil {
                activityArr = NSMutableArray()
            }

            for activity in diaryModel?.reasonArray ?? [] {
                let reasonDic = ["activity": activity, "timeStamp": diaryModel?.timeStampStr]
                activityArr?.add(reasonDic)
            }
            activityArr?.write(toFile: activityFilePath, atomically: true)

            let flag = hisDictionary?.write(toFile: filePath, atomically: true)
            if flag == true {

                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "createSucceed"), object: nil)
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "addDone"), object: nil)

                SVProgressHUD.showSuccess(withStatus: "创建成功")
                SVProgressHUD.dismiss(withDelay: 2.0) {
                    // 坏心情提供弹层
//                    self.dismiss(animated: true)
                    self.dismiss(animated: true) { [weak self] in
                        guard let `self` = self else {return}
                        
                        if self.isBadXinqing {
                            self.showComfortDialogue()
                        }
                    }
                }
            } else {
                SVProgressHUD.showError(withStatus: "创建失败")
                SVProgressHUD.dismiss(withDelay: 2.0)
            }
            
            UserDefaults.standard.set(nil, forKey: textView_cache)
            
        } catch {
            print(error)
        }

    }
    
    private func showComfortDialogue() {
        
        if self.checkTodayDiary(timeStamp: diaryModel?.timeStampStr ?? ""){
            
            let saveView = DiarySaveSuccessView()
            saveView.frame.size = .init(width: 280, height: 275)
            saveAlert = CustomDialogueController.create(with: saveView)
            weak var weakSaveAlert = saveAlert
            saveView.didTouchUpInside {
                weakSaveAlert?.dismiss(animated: true, completion: nil)
                
                let dialogue = ComfortDialogueView()
                dialogue.frame.size = .init(width: AppWidth - 40, height: (AppWidth - 40)*0.88)
                self.alert = CustomDialogueController.create(with: dialogue)
                weak var weakAlert = self.alert
                dialogue.didTouchUpInside {
                    weakAlert?.dismiss(animated: true, completion: nil)
                }
                
                UIApplication.shared.keyWindow?.rootViewController?.present(self.alert!, animated: true)
            }
            
            UIApplication.shared.keyWindow?.rootViewController?.present(saveAlert!, animated: true)
            
        }else{
            
            let dialogue = ComfortDialogueView()
            dialogue.frame.size = .init(width: AppWidth - 40, height: (AppWidth - 40)*0.88)
            self.alert = CustomDialogueController.create(with: dialogue)
            weak var weakAlert = self.alert
            dialogue.didTouchUpInside {
                weakAlert?.dismiss(animated: true, completion: nil)
            }
            
            UIApplication.shared.keyWindow?.rootViewController?.present(self.alert!, animated: true)
            
        }
        
    }
    
    private func checkTodayDiary(timeStamp:String) -> Bool{//检查是否是当天第一个日记

        //日记必有心情，用心情的时间戳来判断当天是否已经有过日记
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String

        let moodFilePath = docPath + "/mood.plist"
        let moodArr = NSMutableArray(contentsOfFile: moodFilePath) as! [[String:String]]

        for dict in moodArr {
            
            let tempTimeStamp:String = dict["timeStamp"] ?? ""
            let diaryTimeStamp:String = timeStamp
            
            if NSString.getYear(tempTimeStamp) == NSString.getYear(diaryTimeStamp) && NSString.getMonth(tempTimeStamp) == NSString.getMonth(diaryTimeStamp) && NSString.getDay(tempTimeStamp) == NSString.getDay(diaryTimeStamp){
                
                return false
            }
            
        }
        
        return true
        
  
    }
    
}

extension AddReasonViewController: UITextViewDelegate {
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        
        diaryModel?.reasonArray = selectArray
        let editAttributesContentVC = AddDiaryContentViewController.init()
        editAttributesContentVC.diaryModel = diaryModel
        editAttributesContentVC.isBadXinqing = self.isBadXinqing
        navigationController?.pushViewController(editAttributesContentVC, animated: true)
        
        return false
        
        guard textView.text == "有更多想告诉我的吗？" else { return true }
        
        textView.textColor = .black
        textView.text = ""
        
        return true
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        // 去掉字数限制
//        if textView.text.count > 500 {
//            textView.text = (textView.text as NSString).substring(to: 499)
//            return false
//        }
        return true
    }
    
    func textViewDidChange(_ textView: UITextView) {
        
        if selectArray?.count ?? 0 > 0 || (textView.text.count > 0 && textView.text != "有更多想告诉我的吗？") {
            btn.isEnabled = true
            btn.layer.borderColor = UIColor.black.cgColor
        } else {
            btn.isEnabled = false
            btn.layer.borderColor = UIColor.hexColor(hex: "#8f8f8f").cgColor
        }
        
        UserDefaults.standard.set(textView.text, forKey: textView_cache)
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        
        if selectArray?.count ?? 0 > 0 || (textView.text.count > 0 && textView.text != "有更多想告诉我的吗？") {
            btn.isEnabled = true
            btn.layer.borderColor = UIColor.black.cgColor
        } else {
            btn.isEnabled = false
            btn.layer.borderColor = UIColor.hexColor(hex: "#8f8f8f").cgColor
        }
        
        guard textView.text == "有更多想告诉我的吗？" || textView.text.count == 0 else { return }
        
        textView.textColor = UIColor.hexColor(hex: "#8f8f8f")
        textView.text = "有更多想告诉我的吗？"
        
    }
}

extension AddReasonViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let page = Int(collectionView.contentOffset.x / collectionView.width)
        pageControl.currentPage = page
        
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let marginX = 25.0
        let itemLength = (Double(collectionView.width) - marginX * 5) / 4
        
        if isFullScreen {
            if screen_width >= 414.0 {
                return CGSize(width: itemLength, height: 105.0)
            } else if screen_width > 375.0 {
                return CGSize(width: itemLength, height: 90.0)
            }
        }
        return CGSize(width: itemLength, height: 70.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if isFullScreen {
            return UIEdgeInsets(top: 25.0, left: 25.0, bottom: 0, right: 25.0)
        }
        return UIEdgeInsets(top: 0, left: 25.0, bottom: 0, right: 25.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
//        if isFullScreen {
            return 25.0
//        }
//        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
//        if isFullScreen {
            return 25.0
//        }
//        return 0
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int { reasonArray.count }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { reasonArray[section].count }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell: AddReasonCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddReasonCollectionViewCell", for: indexPath) as! AddReasonCollectionViewCell
        
        
        if let text:String = reasonArray[indexPath.section][indexPath.row]["text"] as? String {
            
            cell.label.text = text
//            if text.count > 0{
//                cell.shouldShow = true
//            }else{
//                cell.shouldShow = false
//            }
        }
        
        if let imgName:String = reasonArray[indexPath.section][indexPath.row]["imgName"] as? String {
            cell.imgV.image = UIImage(named: imgName)
        }


        if selectArray?.contains(cell.label.text ?? "") == true {
            cell.isSelectCell = true
        } else {
            cell.isSelectCell = false
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        view.endEditing(true)
        
        
        if let text:String = reasonArray[indexPath.section][indexPath.row]["text"] as? String{
            
            
            if text.count == 0{
                return
            }
            
            if selectArray?.contains(text) == true {
                selectArray = selectArray?.filter { $0 != text }
            } else {
                selectArray?.append(text)
            }
            collectionView.reloadData()
                
            if selectArray?.count ?? 0 > 0 || (textView.text.count > 0 && textView.text != "有更多想告诉我的吗？") {
                btn.isEnabled = true
                btn.layer.borderColor = UIColor.black.cgColor
            } else {
                btn.isEnabled = false
                btn.layer.borderColor = UIColor.hexColor(hex: "#8f8f8f").cgColor
            }
            
        }
        
    }
    
}

